/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.yihaodian.remote.RemoteYihaodianOrderServiceImpl
   Module Description   :

   Date Created      : 2011/12/8
   Original Author   : jeff.ma
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.yihaodian.remote;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;

import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.FileUtils;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.core.sms.service.SmsService;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.yihaodian.service.YihaodianOrderService;
import com.yihaodian.order.entity.OrderInfo;
import com.yihaodian.order.entity.OrderRequest;
import com.yihaodian.order.entity.OrderResponse;
import com.yihaodian.order.remote.OrderService;

/**
 * @author jeff.ma
 * 
 */
public class RemoteYihaodianOrderServiceImpl implements RemoteYihaodianOrderService {

	private final Logger logger = LoggerFactory.getLogger(RemoteYihaodianOrderServiceImpl.class);

	private String checkCode = "5623-16-7897-55-72713-5071-874118-48-94";
	@Autowired
	private OrderService yihaodianRemoteOrderService;
	@Autowired
	private YihaodianOrderService yihaodianOrderService;
	@Autowired
	private SmsService smsService;
	private String noticeSMS = "18621771251";

	/** default constructor */
	public RemoteYihaodianOrderServiceImpl() {
	}

	/**
	 * @param yihaodianRemoteOrderService the yihaodianRemoteOrderService to set
	 */
	public void setYihaodianRemoteOrderService(OrderService yihaodianRemoteOrderService) {
		this.yihaodianRemoteOrderService = yihaodianRemoteOrderService;
	}

	/**
	 * @param yihaodianOrderService the yihaodianOrderService to set
	 */
	public void setYihaodianOrderService(YihaodianOrderService yihaodianOrderService) {
		this.yihaodianOrderService = yihaodianOrderService;
	}

	/**
	 * @param smsService the smsService to set
	 */
	public void setSmsService(SmsService smsService) {
		this.smsService = smsService;
	}

	/**
	 * @return the noticeSMS
	 */
	public String getNoticeSMS() {
		return noticeSMS;
	}

	/**
	 * @param noticeSMS the noticeSMS to set
	 */
	public void setNoticeSMS(String noticeSMS) {
		this.noticeSMS = noticeSMS;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml",
				"applicationContext-*.xml" });
		String username = System.getenv("USERNAME");
		if (StringUtils.isBlank(username)) {
			username = System.getenv("USER");
		}
		if (StringUtils.isBlank(username)) {
			username = "test00";
		}
		User tester = new User(username);
		SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(tester, "password"));

		RemoteYihaodianOrderServiceImpl service = new RemoteYihaodianOrderServiceImpl();
		service.setYihaodianOrderService(ctx.getBean(YihaodianOrderService.class));
		service.setYihaodianRemoteOrderService(ctx.getBean(OrderService.class));
		service.setSmsService(ctx.getBean(SmsService.class));
		Date start = null;
		Date end = null;
		if ((args != null) && (args.length == 2)) {
			start = DateUtil.convertStringToDate("yyyyMMddHHmmss", args[0]);
			end = DateUtil.convertStringToDate("yyyyMMddHHmmss", args[1]);
		}
		service.syncOrders(start, end);
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param checkCode the checkCode to set
	 */
	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.yihaodian.remote.RemoteOrderService#syncOrders(java.util.Date, java.util.Date)
	 */
	@Override
	public List<Orders> syncOrders(Date start, Date end) {
		List<Orders> result = new ArrayList();
		int count = 0;

		if (start == null) {
			// 若未指定起始时间由六小时前开始抓
			start = DateUtil.incrementMinutes(-360).getTime();
		}
		if (end == null) {
			// 抓起始时间后面五小时订单 (外站统一付款后一小时才做订单下载)
			Calendar cal = Calendar.getInstance();
			cal.setTime(start);
			cal.add(Calendar.MINUTE, 300);
			end = cal.getTime();
		}
		// 2：订单付款日期, 5：订单更新日期
		OrderRequest req = new OrderRequest(checkCode, 2);
		req.setStartDateTime(DateUtil.convertDateToString("yyyyMMddHHmmss", start));
		req.setEndDateTime(DateUtil.convertDateToString("yyyyMMddHHmmss", end));
		// 38:可以发货（已送仓库）
		req.getInfo().getOrder().getOrderStatusList().add(38L);

		try {
			// 初始由第一页取得
			int page = 1;
			for (int i = 1; i <= page; i++) {
				// 设定页数
				req.setCurPage(Integer.valueOf(i));
				logger.debug("req:{}", req);
				OrderResponse res = yihaodianRemoteOrderService.getOrders(req);
				logger.debug("res:{}", res);

				if ((res.getOrderInfos() == null) || (res.getErrInfos() != null)) {
					break;
				}

				for (OrderInfo o : res.getOrderInfos()) {
					try {
						// 逐笔同步订单
						Orders order = yihaodianOrderService.syncOrder(o);
						if (order != null) {
							// 回传耀点订单物件
							result.add(order);
						}
					} catch (Throwable e) {
						// 记录错误, 继续转下一笔
						logger.error("转订单失败,outerOrderId:" + o.getOrder().getOrderCode(), e);
						FileUtils.writeStringToFile(new File(o.getOrder().getOrderCode() + ".xml"), StringUtils.toXML(o, true));
					}
				}
				// 重新计算正确页数
				page = res.getOrderCount().intValue() / req.getPageRows().intValue();
				count = res.getOrderCount().intValue();
				if (res.getOrderCount().intValue() % req.getPageRows().intValue() != 0) {
					// 若馀数不为 0, 页数补正 +1
					page += 1;
				}
			}
			if (count != result.size()) {
				// 若耀点订单与回传笔数不相符, 提示简讯 , 应该某笔错误
				for (String m : StringUtils.split(noticeSMS, ",")) {
					smsService.sendSms(m, "一号店转订单:" + req.getStartDateTime() + "~" + req.getEndDateTime() + ":" + count + "/"
							+ result.size() + "笔", "");
				}
			}
		} catch (Exception e) {
			for (String m : StringUtils.split(noticeSMS, ",")) {
				smsService.sendSms(m, "一号店转订单失败," + StringUtils.left(e.getMessage(), 60), "");
			}
			logger.error("转订单失败:" + req.getStartDateTime() + "~" + req.getEndDateTime(), e);
		}
		logger.info("转订单:{}~{}: {} 笔", new Object[] { req.getStartDateTime(), req.getEndDateTime(), result.size() });

		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.yaodian100.ec.yihaodian.remote.RemoteOrderService#syncOrder(java.lang.Long)
	 */
	@Override
	public Orders syncOrder(Long id) {
		Orders order = null;
		// OrderRequest req = new OrderRequest(checkCode);
		// order = yihaodianOrderService.syncOrder(null);
		return order;
	}

}
